package com.bjfu.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjfu.common_utils.JwtUtils;
import com.bjfu.common_utils.R;
import com.bjfu.eduorder.entity.Order;
import com.bjfu.eduorder.service.OrderService;
import com.bjfu.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Guli
 * @since 2020-07-18
 */
@RestController
@RequestMapping("/eduorder/order")
//@CrossOrigin
@Api(tags = "课程订单")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @ApiOperation("1.生成订单")
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request){
        if (request.getHeader("token") == null) {
            throw new GuliException(28004,"请先登录");
        }
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        // 创建订单,返回订单号
        String orderNo = orderService.createOrders(courseId,memberId);
        return R.ok().data("orderId",orderNo);
    }

    @ApiOperation("2.根据订单号获取订单")
    @GetMapping("getOrder/{orderId}")
    public R getOrder(@PathVariable String orderId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("order",order);
    }

    @ApiOperation("2.根据课程id和用户id查询订单状态")
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1); // 支付状态 1代表已经支付
        int count = orderService.count(wrapper);
        if (count > 0) {
            return true;
        }else {
            return false;
        }
    }

}

